import { contextBridge, ipcRenderer } from 'electron'

// 监听来自主进程的'message'事件
ipcRenderer.on('update-message', (_, message) => {
  alert(message);
});

ipcRenderer.on('update-ready', (_event, message) => {
  const notification = new Notification('应用更新', {
    body: message,
    icon: '../public/rb.ico',
  });
  setTimeout(() => notification.close(), 5000);
});
if (Notification.permission !== 'granted') {
  Notification.requestPermission().then(permission => {
    if (permission === 'granted') {
      console.log('用户已授权通知');
    } else {
      console.warn('用户未授权通知');
    }
  });
}

contextBridge.exposeInMainWorld('ipcRenderer', {
  on(...args: Parameters<typeof ipcRenderer.on>) {
    const [channel, listener] = args
    return ipcRenderer.on(channel, (event, ...args) => listener(event, ...args))
  },
  off(...args: Parameters<typeof ipcRenderer.off>) {
    const [channel, ...omit] = args
    return ipcRenderer.off(channel, ...omit)
  },
  send(...args: Parameters<typeof ipcRenderer.send>) {
    const [channel, ...omit] = args
    return ipcRenderer.send(channel, ...omit)
  },
  invoke(...args: Parameters<typeof ipcRenderer.invoke>) {
    const [channel, ...omit] = args
    return ipcRenderer.invoke(channel, ...omit)
  },
})

// 文件处理
contextBridge.exposeInMainWorld('fileAPI', {
  navigateWithPlaywright: (url:any, orderNumbersArray:any, isHeadless:boolean) => ipcRenderer.send('navigate-with-playwright', url, orderNumbersArray, isHeadless),
  downloadTemplate: async () => {
    try {
      return await ipcRenderer.invoke('download-template');
    } catch (error) {
      console.error('Error fetching template:', error);
      return null;
    }
  },
  processExcelFile: (fileBuffer: ArrayBuffer) => ipcRenderer.invoke('process-excel-file', fileBuffer),
  readExcelData: (fileBuffer: ArrayBuffer) => ipcRenderer.invoke('read-excel-data', fileBuffer),
  openFile: (filePath: string) => ipcRenderer.invoke('open-file', filePath),
  showItemInFolder: (filePath: string) => ipcRenderer.invoke('show-item-in-folder', filePath),
  getFileFullPath: (file: File) => {
      if (!file || !(file instanceof File)) {
        throw new Error('无效的文件对象: 必须是File类型');
      }
      return ipcRenderer.invoke('get-file-full-path', file);
  },
  // 获取桌面路径
  getDesktopPath: () => ipcRenderer.invoke('get-desktop-path'),
  // 确保目录存在
  ensureDirectoryExists: (dirPath: string) => ipcRenderer.invoke('ensure-directory-exists', dirPath),
  // 保存文件
  saveFile: (filePath: string, fileContent: any) => ipcRenderer.invoke('save-file', filePath, fileContent),
  // 读取目录
  readDirectory: (dirPath: string) => ipcRenderer.invoke('read-directory', dirPath),
  // 读取文件
  readFile: (filePath: string) => ipcRenderer.invoke('read-file', filePath),
  // 写入文件
  writeFile: (filePath: string, content: string) => ipcRenderer.invoke('write-file', filePath, content),
  // 删除文件
  deleteFile: (filePath: string) => ipcRenderer.invoke('delete-file', filePath),
  // 显示文件选择对话框
  showOpenDialog: (options: any) => ipcRenderer.invoke('show-open-dialog', options),
  // 检查文件是否存在
  checkFileExists: (filePath: string) => ipcRenderer.invoke('check-file-exists', filePath),
});

// electron处理
contextBridge.exposeInMainWorld('electron', {
  send: (channel: any, data: any) => { ipcRenderer.send(channel, data); }, // 从渲染进程发送消息到主进程的示例函数
  receive: (channel: any, func: any) => { ipcRenderer.on(channel, (_event, ...args) => func(...args)); } // 从主进程接收消息到渲染进程的示例函数注册器
});

contextBridge.exposeInMainWorld('electronAPI', {
  send: (channel: string, data: any) => ipcRenderer.send(channel, data),
  getPath: (name: string) => ipcRenderer.invoke('get-app-path', name),
  getPluginPath: (pluginName: any) => {
    return ipcRenderer.invoke('get-plugin-path', pluginName);
  },
  getPluginHtmlPath: (pluginName: any) => {
    return ipcRenderer.invoke('get-plugin-html-path', pluginName);
  },
  getMainfestPath: (pluginName: any) => {
    return ipcRenderer.invoke('get-mainfest-path', pluginName);
  },
  createPluginWindow: (pluginName: string, htmlPath: string) => 
    ipcRenderer.invoke('create-plugin-window', pluginName, htmlPath),
  closeWindow: () => ipcRenderer.send('close-window'),
  isWindowOpen: (pluginName: string) => ipcRenderer.invoke('is-window-open', pluginName),
  toggleMaximize: () => ipcRenderer.invoke('toggle-maximize'),
  minimizeWindow: () => ipcRenderer.invoke('minimize-window'),
  loadPlugin: (pluginId: string) => ipcRenderer.invoke('load-plugin', pluginId),
  writeData: () => ipcRenderer.invoke('write-data'),
  executeChildProcess: (command: any) => ipcRenderer.invoke('execute-child-process', command),
  runPlugin: (pluginId: string) => ipcRenderer.invoke('run-plugin', pluginId),
  downloadPlugin: (pluginId: string, downloadUrl: string) => ipcRenderer.invoke('download-plugin', pluginId, downloadUrl),
  getSheetIds: () => ipcRenderer.invoke('getSheetIds'),
  saveSheetIds: (ids: string[]) => ipcRenderer.invoke('saveSheetIds', ids),
  readCellData: (spreadsheetId: string, range: string) => ipcRenderer.invoke('read-cell-data', spreadsheetId, range),
  readColumnData: (spreadsheetId: any, range: any) => ipcRenderer.invoke('google-api:readColumnData', spreadsheetId, range),
  readRowData: (spreadsheetId: string, range: string) => ipcRenderer.invoke('google-api:readRowData', spreadsheetId, range),
  updateRowData: (spreadsheetId: string, plmCode: string, rowData: string[], range: string) => ipcRenderer.invoke('google-api:updateRowData', spreadsheetId, plmCode, rowData, range),
  getSheetNames: (spreadsheetId: string) => ipcRenderer.invoke('getSheetNames', spreadsheetId),
  updatePartialColumns: (spreadsheetId: string, sheetName: string, plmCode: string, updates: Record<number, string>, range: string) =>
      ipcRenderer.invoke('update-partial-columns', spreadsheetId, sheetName, plmCode, updates, range),
  saveSettings: (settings: any) => ipcRenderer.invoke('save-settings', settings),
  getUserSettings: () => ipcRenderer.invoke('get-user-settings'),
  sendMonitoringData: (data: any) => ipcRenderer.invoke('send-monitoring-data', data),
  getBatchCombineOrders: () => ipcRenderer.invoke('get-batch-combine-orders'),
  
  // 控制台监控相关API (为了兼容性也在这里添加)
  getConsoleLogs: (limit?: number) => ipcRenderer.invoke('get-console-logs', limit),
  clearConsoleLogs: () => ipcRenderer.invoke('clear-console-logs'),
  startConsoleMonitoring: () => ipcRenderer.invoke('start-console-monitoring'),
  stopConsoleMonitoring: () => ipcRenderer.invoke('stop-console-monitoring'),
  addConsoleLog: (level: string, message: string) => ipcRenderer.invoke('add-console-log', level, message),
  onConsoleLog: (callback: (log: any) => void) => {
    ipcRenderer.on('console-log', (_, log) => callback(log));
  },
  onConsoleLogsBatch: (callback: (logs: any[]) => void) => {
    ipcRenderer.on('console-logs-batch', (_, logs) => callback(logs));
  },
  onConsoleCleared: (callback: () => void) => {
    ipcRenderer.on('console-cleared', () => callback());
  },
  removeConsoleLogListeners: () => {
    ipcRenderer.removeAllListeners('console-log');
    ipcRenderer.removeAllListeners('console-logs-batch');
    ipcRenderer.removeAllListeners('console-cleared');
  }
});

// 通知处理
contextBridge.exposeInMainWorld('notification', {
  create(title: string, options: NotificationOptions) {
    return new Notification(title, options);
  },
  requestPermission() {
    return Notification.requestPermission();
  },
});

// playwright处理
contextBridge.exposeInMainWorld('playwrightAPI', {
  openBrowser: (url: string, headless: boolean) => ipcRenderer.send('open-browser', url, headless),
  loginGPO: (url: string, headless: boolean) => ipcRenderer.invoke('login-GPO', url, headless),
  orderListEntry: (url: string, headless: boolean) => ipcRenderer.send('orderList-entry', url, headless),
  reportListEntry: (url: string, headless: boolean) => ipcRenderer.send('reportList-entry', url, headless),
  // runBatchCombine: (address: string, headless: boolean, orders: string[]) => {
  //   return ipcRenderer.invoke('run-batch-combine', address, headless, orders);
  // },
  runNewSubcontract: (address: string, headless: boolean, allCellData: any) => {
    return ipcRenderer.invoke('run-new-subcontract', address, headless, allCellData);
  },
});

// docx处理
contextBridge.exposeInMainWorld('docxAPI', {
  processWordFile: (pluginName: string, reportData: any[]) => 
    ipcRenderer.invoke('process-word-file', pluginName, reportData),
  saveWordFile: (buffer: ArrayBuffer, filename: string ) => 
    ipcRenderer.invoke('save-word-file', buffer, filename),
  getWordTemplate: (pluginName: string) => ipcRenderer.invoke('get-word-template', pluginName),
});

// htmlUI处理
contextBridge.exposeInMainWorld('htmlUIAPI', {
  injectWindowControls: () => {
    const controlsHTML = `
      <div class="buttons drag-region" id="window-controls" style="position: fixed; top: 0; right: 0; z-index: 9999;">
        <button class="minimize" onclick="window.electronAPI.minimizeWindow()">
          <svg viewBox="0 0 10.2 1" width="10" height="10"><rect height="1" width="10.2" y="50%" x="0"></rect></svg>
        </button>
        <button class="maximize" onclick="window.electronAPI.toggleMaximize()">
          <svg viewBox="0 0 10 10" width="10" height="10"><path d="M0,0v10h10V0H0z M9,9H1V1h8V9z"></path></svg>
        </button>
        <button class="close" onclick="window.electronAPI.closeWindow()">
          <svg viewBox="0 0 10 10" width="10" height="10"><polygon points="10.2,0.7 9.5,0 5.1,4.4 0.7,0 0,0.7 4.4,5.1 0,9.5 0.7,10.2 5.1,5.8 9.5,10.2 10.2,9.5 5.8,5.1"></polygon></svg>
        </button>
      </div>
      <style scoped>
        .drag-region {
          display: flex;
          position: fixed;
          top: 0;
          left: 0;
          width: 100%;
          height: 30px;
          -webkit-app-region: drag;
          background: transparent;
          justify-content: flex-end;
          align-items: center;
          padding-right: 10px;
        }

        button {
          width: 40px;
          margin-left: -5px;
          border: 0;
          outline: 0;
          background: transparent;
          transition: 0.2s;
          -webkit-app-region: no-drag;
        }

        button svg path, 
        button svg rect, 
        button svg polygon {
          fill: #ffffff;
        }

        button svg {
          width: 10px;
          height: 10px;
        }

        .close:hover {
          svg polygon {
            fill: #ff0000;
          }
        }

        .maximize:hover {
          svg path {
            fill: #53535f;
          }
        }

        .minimize:hover {
          svg rect {
            fill: #53535f;
          }
        }
      </style>
    `;
    document.body.insertAdjacentHTML('afterbegin', controlsHTML);
  },
});

// 日志处理
contextBridge.exposeInMainWorld('logAPI', {
  sendLog: (message: string = '[empty message]', type = 'info', details?: string) => {
    // 强制参数校验
    const validatedMessage = message?.toString() || 'invalid message';
    const validatedType = ['info','warn','error','debug','verbose','silly'].includes(type) ? type : 'info';
    
    ipcRenderer.send('log-message', { 
        message: validatedMessage,
        type: validatedType,
        details: details?.toString() || ''
    });
  },
  onLogMessage: (callback: (log: any) => void) => {
      ipcRenderer.on('log-message', (event, log) => {
          callback({
              message: (log?.message || '').toString(),
              type: ['info','warn','error','debug','verbose','silly'].includes(log?.type) ? log.type : 'info',
              details: (log?.details || '').toString()
          });
      });
  }
});

// 存储当前运行的任务ID
let currentPluginTaskId: string | null = null;

// 监听插件脚本启动事件
ipcRenderer.on('plugin-script-started', (_event, { taskId }) => {
  console.log(`插件脚本已启动，任务ID: ${taskId}`);
  currentPluginTaskId = taskId;
});

contextBridge.exposeInMainWorld('pluginAPI', {
  checkPluginUpdate: (pluginId: string) => ipcRenderer.invoke('check-plugin-update', pluginId),
  deletePlugin: (pluginId: string) => ipcRenderer.invoke('delete-plugin', pluginId),
  runPluginScript: (params: {pluginName: string, script: string, args?: any[]}) => ipcRenderer.invoke('run-plugin-script', params),
  stopPluginScript: () => {
    if (currentPluginTaskId) {
      console.log(`停止插件脚本，任务ID: ${currentPluginTaskId}`);
      const result = ipcRenderer.invoke('stop-plugin-script', { taskId: currentPluginTaskId });
      currentPluginTaskId = null;
      return result;
    } else {
      console.warn('没有正在运行的插件脚本任务');
      return Promise.resolve({ success: false, error: '没有正在运行的插件脚本任务' });
    }
  },
  getCurrentTaskId: () => currentPluginTaskId,
  // 添加获取所有正在运行的插件任务的方法
  getRunningPluginTasks: () => ipcRenderer.invoke('get-running-plugin-tasks')
});

contextBridge.exposeInMainWorld('pyAPI', {
  runpyfile: (data: {scriptPath?: string, filePath?: string, fileName?: string, pluginName?: string, args?: any[]}) => 
    ipcRenderer.invoke('run-pyfile', data),
  runpyexe: (data: {exeName?: string, args?: any[], pluginName?: string}) => 
    ipcRenderer.invoke('run-pyexe', data),
  
  // Python环境检查
  checkPythonEnvironment: () => ipcRenderer.invoke('check-python-environment'),
  
  // 检查Python环境（为插件提供）
  checkPythonEnvironmentForPlugin: (pluginName?: string) => ipcRenderer.invoke('plugin-check-python-environment', pluginName),
  
  // 检查并下载Python环境（整合功能）
  checkAndDownloadPythonEnvironment: (pluginName: string) => ipcRenderer.invoke('check-and-download-python-environment', pluginName),
  
  onPythonLogOutput: (callback: (logData: {type: 'stdout' | 'stderr', data: string, timestamp: string}) => void) => {
    ipcRenderer.on('python-log-output', (_event, logData) => callback(logData));
  },
  
  // 监听Python进程结束事件
  onPythonProcessEnded: (callback: (endData: {code: number, success: boolean, timestamp: string}) => void) => {
    ipcRenderer.on('python-process-ended', (_event, endData) => callback(endData));
  },
  
  // 监听Python进程错误事件
  onPythonProcessError: (callback: (errorData: {error: string, timestamp: string}) => void) => {
    ipcRenderer.on('python-process-error', (_event, errorData) => callback(errorData));
  },
  
  // 监听Python环境状态事件
  onPythonEnvironmentStatus: (callback: (statusData: {status: string, message: string, progress?: number}) => void) => {
    ipcRenderer.on('python-environment-status', (_event, statusData) => callback(statusData));
  },
  
  // 移除Python相关的事件监听器
  removePythonLogListeners: () => {
    ipcRenderer.removeAllListeners('python-log-output');
    ipcRenderer.removeAllListeners('python-process-ended');
    ipcRenderer.removeAllListeners('python-process-error');
    ipcRenderer.removeAllListeners('python-environment-status');
  }
});

// 控制台监控API
contextBridge.exposeInMainWorld('consoleAPI', {
  // 获取控制台日志
  getConsoleLogs: (limit?: number) => ipcRenderer.invoke('get-console-logs', limit),
  
  // 清空控制台日志
  clearConsoleLogs: () => ipcRenderer.invoke('clear-console-logs'),
  
  // 开始控制台监控
  startConsoleMonitoring: () => ipcRenderer.invoke('start-console-monitoring'),
  
  // 停止控制台监控
  stopConsoleMonitoring: () => ipcRenderer.invoke('stop-console-monitoring'),
  
  // 手动添加日志条目
  addConsoleLog: (level: string, message: string) => ipcRenderer.invoke('add-console-log', level, message),
  
  // 监听实时日志
  onConsoleLog: (callback: (log: any) => void) => {
    ipcRenderer.on('console-log', (_, log) => callback(log));
  },
  
  // 监听批量日志
  onConsoleLogsBatch: (callback: (logs: any[]) => void) => {
    ipcRenderer.on('console-logs-batch', (_, logs) => callback(logs));
  },
  
  // 监听日志清空事件
  onConsoleCleared: (callback: () => void) => {
    ipcRenderer.on('console-cleared', () => callback());
  },
  
  // 移除所有控制台相关的事件监听器
  removeConsoleLogListeners: () => {
    ipcRenderer.removeAllListeners('console-log');
    ipcRenderer.removeAllListeners('console-logs-batch');
    ipcRenderer.removeAllListeners('console-cleared');
  }
});

// Node.js环境检查API
contextBridge.exposeInMainWorld('nodeAPI', {
  // 检查Node.js环境状态
  checkNodeEnvironment: () => ipcRenderer.invoke('check-node-environment'),
  
  // 安装便携版Node.js
  installPortableNode: () => ipcRenderer.invoke('install-portable-node'),
  
  // 检查插件依赖
  checkPluginDependencies: (pluginPath: string) => 
    ipcRenderer.invoke('check-plugin-dependencies', pluginPath),
  
  // 获取Node.js可执行文件路径
  getNodeExecutablePath: () => ipcRenderer.invoke('get-node-executable-path'),
  
  // 监听Node.js安装进度
  onNodeInstallProgress: (callback: (progress: any) => void) => {
    ipcRenderer.on('node-install-progress', (_, progress) => callback(progress));
  },
  
  // 监听插件依赖安装进度
  onPluginDependencyProgress: (callback: (data: { message: string; progress: number }) => void) => {
    ipcRenderer.on('plugin-dependency-progress', (_, data) => callback(data));
  },
  
  // 移除Node.js相关的事件监听器
  removeNodeListeners: () => {
    ipcRenderer.removeAllListeners('node-install-progress');
    ipcRenderer.removeAllListeners('plugin-dependency-progress');
  }
});